package main

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
)

/*
mylog
*/
type formatter struct {
	x     interface{}
	force bool
	quote bool
}

func MyPrintf(format string, a ...interface{}) {
	if SY.IsPublic == 0 {
		fmt.Printf(format, wrap(a, false)...)
	}
}

func wrap(a []interface{}, force bool) []interface{} {
	w := make([]interface{}, len(a))
	for i, x := range a {
		w[i] = formatter{x: x, force: force}
	}
	return w
}

func IntToString(i int) string {
	return strconv.Itoa(i)
}

/*
取当前系统信息
amd64 linux
(amd64 ,  darwin)
386 , windows
*/
func GetOsInfo() (string, string) {
	arch := runtime.GOARCH
	goos := runtime.GOOS
	return arch, goos
}

/*
取当前路径
*/
func GetCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0])) //返回绝对路径  filepath.Dir(os.Args[0])去除最后一个元素的路径
	if err != nil {
		//log.Fatal(err)
		return ""
	}
	return strings.Replace(dir, "\\", "/", -1) //将\替换成/
}

//生成32位md5字串
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

//生成Guid字串
func GetGuid() string {
	b := make([]byte, 48)
	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		return ""
	}
	return GetMd5String(base64.URLEncoding.EncodeToString(b))
}

func httpGet(url string) string {
	resp, err := http.Get(url)
	//"http://www.01happy.com/demo/accept.php?id=1"
	if err != nil {
		// handle error
		return ""
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		return ""
	}
	return (string(body))
}

func httpPost(url string, values string) string {
	//	resp, err := http.Post("http://localhost/gotest.php", "application/x-www-form-urlencoded", strings.NewReader("name=wenson&sex=男"))
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(values))
	if err == nil {
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err == nil {
			return (string(body))
		}
	} else {
		fmt.Println(err)
		return ""
	}
	return ""
}
